#ifndef BLOCK_H
#define BLOCK_H

#include <stdint.h>
#include "common.h"

// 块设备状态 - 每个打开的文件一个实例
typedef struct BlockDriverState {
    int64_t total_sectors;
    int cluster_size;
    void *opaque;           // 指向 QCow2State
    char *filename;
    int refcount;           // 引用计数
    struct BlockDriverState *next;  // 链表支持
} BlockDriverState;

typedef struct BlockDriver {
    const char *format_name;
    struct BlockDriver *next;
    int (*bdrv_open)(BlockDriverState *bs, const char *filename);
    int (*bdrv_close)(BlockDriverState *bs);
    int64_t (*bdrv_getlength)(BlockDriverState *bs);
    int (*bdrv_read)(BlockDriverState *bs, int64_t offset,
                     uint8_t *buf, int64_t bytes);
    int (*bdrv_write)(BlockDriverState *bs, int64_t offset,
                      const uint8_t *buf, int64_t bytes);
} BlockDriver;

// 块设备管理器
typedef struct BlockBackend {
    BlockDriverState *bs;
    char *name;
    struct BlockBackend *next;
} BlockBackend;

#ifdef __cplusplus
extern "C" {
#endif

// 全局函数
void bdrv_init(void);
BlockDriverState* bdrv_open(const char *filename, const char *driver);
void bdrv_close(BlockDriverState *bs);
int64_t bdrv_getlength(BlockDriverState *bs);
int bdrv_read(BlockDriverState *bs, int64_t offset, uint8_t *buf, int64_t bytes);
int bdrv_write(BlockDriverState *bs, int64_t offset, const uint8_t *buf, int64_t bytes);

// 多文件管理
BlockBackend* blk_new(const char *name);
void blk_unref(BlockBackend *blk);
BlockBackend* blk_by_name(const char *name);
int blk_attach(BlockBackend *blk, BlockDriverState *bs);
BlockDriverState* blk_bs(BlockBackend *blk);

// 工具函数
void bdrv_list(void);  // 列出所有打开的块设备

#ifdef __cplusplus
}
#endif

#endif